//
//  SearchPDViewController.m
//  LazyCat
//
//  Created by rocky on 15/11/16.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "SearchPDViewController.h"
#import "AFNetworkHandler.h"
#import "SearchViewCell.h"
#import "HomeViewController.h"
#import "UIViewController+MMDrawerController.h"
#import "LCLeftViewController.h"
#import "MMDrawerController.h"

@interface SearchPDViewController ()<UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    
    UILabel *headerLable;
    UILabel *headerLable2;
    UIImageView *deleteImg;
    UIButton *delteButton;
    NSString *resultSearchStr; //最终的搜索结果（可以是输入的，也可以是搜索历史）
}
@property (nonatomic,strong) UITextField *textField;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UITableView *tableView;
@property (strong, nonatomic) NSArray *recordArr;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property(nonatomic,strong)MMDrawerController *drawerController;

@end

@implementation SearchPDViewController

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
     [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    [self.textField becomeFirstResponder];
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

    NSArray *arr = [NSUserDefualManager getValueByKey:SCSearchRecord];
    if (arr.count == 0) {
        self.collectionView.hidden = YES;
//        self.tableView.hidden = YES;
    }else {
        self.collectionView.hidden = NO;
//        self.tableView.hidden = NO;
    }
    [self.collectionView reloadData];
//    [self.tableView reloadData];
}
//状态
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

    
    resultSearchStr = @"";
    [self createTopView];
    [self reloadData]; // 获取搜索记录
    self.view.backgroundColor = BackColor;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc ]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = BackColor;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[SearchViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.hidden = YES;
    [self.view addSubview:self.tableView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidKeyBoard:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardshow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardhide:) name:UIKeyboardWillHideNotification object:nil];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}
#pragma mark 当键盘出现或改变时调用
-(void)keyBoardshow:(NSNotification *)notification{
    NSDictionary *info=[notification userInfo];
    NSValue *avalue=[info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect=[self.view convertRect:[avalue CGRectValue] fromView:nil];
    double keyboardHeight=keyboardRect.size.height;//键盘的高度
    [UIView animateWithDuration:0.2 animations:^{
        self.collectionView.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-keyboardHeight-64);
    }];
    
}

-(void)keyBoardhide:(NSNotification *)notification{
    [UIView animateWithDuration:0.2 animations:^{
        self.collectionView.frame = CGRectMake(0, 64, ScreenWidth, ScreenHeight-64);
    }];
}
-(void)hidKeyBoard:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
    [self.textField resignFirstResponder];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
#pragma mark - tableView显示内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tcell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"tcell"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = [self.dataArr[indexPath.row] objectForKey:@"keyword"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"约%@条相关信息",[self.dataArr[indexPath.row] objectForKey:@"count"]];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
    return cell;
}
#pragma mark - tableView点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    HomeViewController *homeVC = [[HomeViewController alloc]init];
    homeVC.searchUrl = [NSString stringWithFormat:@"%@",[self.dataArr[indexPath.row] objectForKey:@"keyword"]];
    LCLeftViewController *leftVC = [[LCLeftViewController alloc]init];
    self.drawerController = [[MMDrawerController alloc]initWithCenterViewController:homeVC leftDrawerViewController:leftVC];
    [self.drawerController setShowsShadow:YES];//左侧有阴影
    self.drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;
    self.drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
    self.drawerController.maximumLeftDrawerWidth = KleftViewW;
    // 添加搜索历史
    NSString *str = [self.dataArr[indexPath.row] objectForKey:@"keyword"];
    if (str.length != 0) {
        //不能为空
        NSString *changedStr = [self.textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (changedStr.length != 0) {
            [NSUserDefualManager addNewRecord:str forKey:SCSearchRecord];
        }
    }
    [self.mm_drawerController setCenterViewController:homeVC withCloseAnimation:YES completion:nil];
    [self.navigationController pushViewController:self.drawerController animated:YES];
}
#pragma mark - 搜索View
-(void)createTopView {//创建头部搜索
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];//底部view
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(10, 29, ScreenWidth - 60, 30)];
    searchView.backgroundColor =  BackColor;
    searchView.layer.cornerRadius = 15;
    [topView addSubview:searchView];//搜索view
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7, 15, 15)];
    img.image = [UIImage imageNamed:@"搜索_r3_c2.png"];
    [searchView addSubview:img];
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(34, 0, ScreenWidth - 100, 30)];
    self.textField.delegate = self;
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [searchView addSubview:self.textField];
    self.textField.placeholder = @"输入商品名称或关键字";
    self.textField.font = [UIFont systemFontOfSize:14];
    // 监听实时更新文本
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showtextFiledContents) name:UITextFieldTextDidChangeNotification object:nil];
    UIButton *cantButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 48, 27, 45, 35)];
    [cantButton setTitle:@"取消" forState:UIControlStateNormal];
    cantButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [cantButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cantButton addTarget:self action:@selector(contAction) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:cantButton];//取消按钮
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 63.5, ScreenWidth, 0.5)];//导航栏下划线
    lineView.alpha = 0.5;
    lineView.backgroundColor = [UIColor lightGrayColor];
    [topView addSubview:lineView];
}
-(void)contAction {//点击取消按钮
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 开始编辑的时候
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    textField.returnKeyType = UIReturnKeySearch;
}
#pragma mark - 实时监听文本输入
- (void) showtextFiledContents{
    NSLog(@"~~~~~~~%@",self.textField.text);
    self.dataArr = [NSMutableArray array];
#warning 搜索的URL还不知道
   // NSString *url = [NSString stringWithFormat:searchOnTimeURL,[[AppData share].username safeString],[Utils md5SignStr],@"100",self.textField.text];
    NSString *url ;
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dic = result;
        if ([[dic objectForKey:@"r"] isEqualToString:@"T"]) {
            self.dataArr = [NSMutableArray array];
            self.dataArr = [dic objectForKey:@"d"];
            if (self.dataArr.count > 0) {
                self.collectionView.hidden = YES;
                self.tableView.hidden = NO;
            }else{
                self.collectionView.hidden = NO;
                self.tableView.hidden = YES;
            }
            NSArray *arr = [NSUserDefualManager getValueByKey:SCSearchRecord];
            if (arr.count == 0) {
                self.collectionView.hidden = YES;
                self.tableView.hidden = YES;
            }else {
                self.collectionView.hidden = NO;
                self.tableView.hidden = NO;
            }
            [self.tableView reloadData];
        }
    }];
}
#pragma mark - UITextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    //搜索事件
    if (textField.text.length > 0) {
        [self searchManager]; // 加入搜索历史
        HomeViewController *homeVC = [[HomeViewController alloc] init];
        homeVC.searchUrl = textField.text;
        LCLeftViewController *leftVC = [[LCLeftViewController alloc]init];
        self.drawerController = [[MMDrawerController alloc]initWithCenterViewController:homeVC leftDrawerViewController:leftVC];
        [self.drawerController setShowsShadow:YES];//左侧有阴影
        self.drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;
        self.drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
        self.drawerController.maximumLeftDrawerWidth = KleftViewW;
        
        [self.mm_drawerController setCenterViewController:homeVC withCloseAnimation:YES completion:nil];
        [self.navigationController pushViewController:self.drawerController animated:YES];
    }else {
        
        [[MessShowView share] showWithMess:@"请输入搜索内容"];
    }
    return YES;
}
// 加入搜索历史
-(void)searchManager {
    if (self.textField.text.length != 0) {
        //不能为空
        NSString *changedStr = [self.textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (changedStr.length != 0) {
            [NSUserDefualManager addNewRecord:self.textField.text forKey:SCSearchRecord];
            
//            [self reloadData];
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 0) {
        return UIEdgeInsetsMake(0, 0, 0, 0);//分别为上、左、下、右
    }else {
        return UIEdgeInsetsMake(0, 0, 0, 0);//分别为上、左、下、右
    }
}
#pragma mark - section个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
#pragma mark - cell个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 1) {
        return 1;
    }else{
        return _recordArr.count;
    }
}
#pragma mark - 每个cell大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(ScreenWidth, 45);
}
#pragma mark - cell之间的距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.0f;
}
#pragma mark - cell显示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.section == 0) {
        cell.lsLable.text = _recordArr[indexPath.item];
    }
    return cell;
}
#pragma mark - 点击历史记录搜索
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSLog(@"%@",_recordArr[indexPath.item]);
        HomeViewController *homeVC = [[HomeViewController alloc] init];
        homeVC.searchUrl = _recordArr[indexPath.item];
        LCLeftViewController *leftVC = [[LCLeftViewController alloc]init];
        self.drawerController = [[MMDrawerController alloc]initWithCenterViewController:homeVC leftDrawerViewController:leftVC];
        [self.drawerController setShowsShadow:YES];//左侧有阴影
        self.drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;
        self.drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
        self.drawerController.maximumLeftDrawerWidth = KleftViewW;
        
        [self.mm_drawerController setCenterViewController:homeVC withCloseAnimation:YES completion:nil];
        [self.navigationController pushViewController:self.drawerController animated:YES];
    }
}
#pragma mark - 头部大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0 ) {
        return CGSizeMake(ScreenWidth, 30);
    }else{
        return CGSizeMake(ScreenWidth, 30);
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (section == 1) {
         return CGSizeMake(ScreenWidth, 0);
    }else{
        return CGSizeMake(ScreenWidth, 45);
    }
}
#pragma mark - 头部视图
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
     if (kind == UICollectionElementKindSectionHeader) {
            UICollectionReusableView *header =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:@"header" forIndexPath:indexPath];
//    if (indexPath.section == 0) {
        if (!headerLable) {
            headerLable =  [[UILabel alloc]init];
            headerLable.frame = CGRectMake(10, 0, ScreenWidth, 30);
            headerLable.text = @"搜索历史记录";
            headerLable.font = [UIFont fontWithName:nil size:14];
            headerLable.textColor = [UIColor grayColor];
            [header addSubview:headerLable];
        }
        
        return header;
//    }else{
// 
//        if (!headerLable2) {
//            headerLable2 =  [[UILabel alloc]init];
//            headerLable2.frame = CGRectMake(10, 0, ScreenWidth, 30);
//             headerLable2.text = @"搜索历史记录";
//            headerLable2.textColor = [UIColor grayColor];
//            [header addSubview:headerLable2];
//        }
//        return header;
//    }
//    }
     }else{// 尾部视图
         UICollectionReusableView *footer =  [collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:@"footer" forIndexPath:indexPath];
         footer.backgroundColor = [UIColor whiteColor];
         if (!deleteImg) {
             deleteImg = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth / 2 - 60, 10, 20, 20 )];
             deleteImg.image = [UIImage imageNamed:@"删除111111"];
             [footer addSubview:deleteImg];
         }
         if (!delteButton) {
             delteButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth / 2 - 60 + 20, 10, 100, 20 )];
             [delteButton setTitle:@"清除搜索历史" forState:UIControlStateNormal];
             [delteButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
             delteButton.titleLabel.font = [UIFont fontWithName:nil size:14];
             [delteButton addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
             
             [footer addSubview:delteButton];
         }
         return footer;
     }
}

-(void)deleteAction
{
    [NSUserDefualManager storageValue:@[] forKey:SCSearchRecord];
    self.collectionView.hidden = YES;
    [self reloadData];
}
// 获取搜索记录
- (void)reloadData {
    _recordArr = [NSArray array];
    _recordArr = [NSUserDefualManager getValueByKey:SCSearchRecord];
    if (_recordArr.count == 0) {
        self.collectionView.hidden = YES;
    }else {
        [self.collectionView reloadData];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
